import React, { useEffect, useState, FC } from 'react'
import styles from './index.module.less'
import { Navigate, useNavigate } from 'react-router-dom'
import { Form, Input, Button, Toast } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import Loading from '@/comopnents/loading'

import { doLogin, getMemberInfo } from '@/utils/my/login'

export default function Login() {

  const navigate = useNavigate()
  // 密码框是否可见
  const [visible, setVisible] = useState<boolean>(false)
  // 是否点击了登录
  const [isLoading, setIsLoading] = useState<boolean>(false)

  // 点击登录
  const loginBtnClick = (info?: any) => {
    setIsLoading(true)
    login(info)
  }

  // 登录请求
  const login = async (data: object) => {
    let res: resType = await doLogin(data)
    // 请求错误
    if (res.code !== 20000) return Toast.show({
      icon: 'fail',
      content: res.message,
      duration: 1000,
      afterClose: () => setIsLoading(false)
    })
    if (res.data.token) {
      localStorage.setItem('token', res.data.token)
      if (localStorage.getItem('token')) {
        Toast.show({
          icon: 'loading',
          content: <CountDownText />,
          duration: 3000,
          afterClose: () => getUserInfo()
        })
      }
    }
  }

  // 倒计时
  const CountDownText: FC = () => {
    const [count, setCount] = useState(3)
    useEffect(() => {
      const interval = window.setInterval(() => {
        setCount(x => {
          if (x > 1) {
            return x - 1
          } else {
            return x
          }
        })
      }, 1000)
      return () => {
        window.clearInterval(interval)
      }
    }, [])
    return <div className={styles.infoJump}>将在{count}秒后跳转到个人中心</div>
  }

  // 获取用户信息
  const getUserInfo = async () => {
    let res: resType = await getMemberInfo()
    if (res.code !== 20000) return Toast.show({
      icon: 'fail',
      content: res.message,
    })
    if (res.data.userInfo) {
      localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
      navigate('/my')
      setIsLoading(false)
    }
  }

  // 表单初始值
  const formInitialVal = {
    username: '17596496508',
    password: '123456'
  }

  useEffect(() => {
    if (localStorage.getItem('token')) {
      navigate("/my")
    }
  }, [])

  return (
    <div className={styles.loginBox}>
      <div className={styles.txBox}>
        <img className={styles.tx} src={require('@/static/logo.png')} alt="" />
      </div>
      <Form className={styles.formBox} requiredMarkStyle='text-required' onFinish={loginBtnClick} initialValues={formInitialVal}>
        <Form.Item className={styles.info} name='username' rules={[{ required: true, message: '请输入用户名/手机号' }, { pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/, message: '请输入正确的手机号' }]} >
          <Input clearable placeholder='用户名/电话' />
        </Form.Item>
        <Form.Item className={styles.info} name='password' rules={[{ required: true, message: '请输入密码' }, { min: 5, max: 12, message: '密码长度应为5~12位之间' }]} extra={
          <div className={styles.eye}>
            {!visible ? (
              <EyeInvisibleOutline onClick={() => setVisible(true)} />
            ) : (
              <EyeOutline onClick={() => setVisible(false)} />
            )}
          </div>
        } >
          <Input clearable type={visible ? 'text' : 'password'} placeholder='请输入密码' />
        </Form.Item>
        <Button className={styles.submit} shape='rounded' type='submit' color='primary' size='large'>
          {
            isLoading ? <Loading></Loading> : <>登录</>
          }
        </Button>
      </Form>
      <div className={styles.bottom}>
        <span onClick={() => navigate('/my/resetpassword')}>找回密码</span>
        <span className={styles.line}>|</span>
        <span onClick={() => navigate('/my/register')}>注册账号</span>
      </div>
    </div >
  )
}
